package com.bgy.sms;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bgy.model.Meetingcreate;
import com.bgy.model.Mmsryxx;
import com.jfinal.kit.PropKit;
import com.jfinal.qyweixin.sdk.api.ApiConfig;
//import com.jfinal.qy.weixin.sdk.api.ApiConfig;
//import com.jfinal.qy.weixin.sdk.api.ApiConfigKit;
//import com.jfinal.qy.weixin.sdk.api.ApiResult;
//import com.jfinal.qy.weixin.sdk.api.ConDepartmentApi;
//import com.jfinal.qy.weixin.sdk.api.ConUserApi;
//import com.jfinal.qy.weixin.sdk.api.SendMessageApi;
//import com.jfinal.qy.weixin.sdk.msg.send.Article;
//import com.jfinal.qy.weixin.sdk.msg.send.News;
//import com.jfinal.qy.weixin.sdk.msg.send.QiYeNewsMsg;
import com.jfinal.qyweixin.sdk.api.ApiConfigKit;
import com.jfinal.qyweixin.sdk.api.ApiResult;
import com.jfinal.qyweixin.sdk.api.ConDepartmentApi;
import com.jfinal.qyweixin.sdk.api.ConUserApi;
import com.jfinal.qyweixin.sdk.api.SendMessageApi;
import com.jfinal.qyweixin.sdk.msg.send.Article;
import com.jfinal.qyweixin.sdk.msg.send.News;
import com.jfinal.qyweixin.sdk.msg.send.QiYeNewsMsg;


/**
 * 后台会议通知类，定期扫描 mms_meetingcreate 表的issend 是否发送标致，
 * 0 尚未发送，然后发微信给所有参与人员，然后设置为1
 * @author Administrator
 *
 */
public class MeetingNotice {
	
	public MeetingNotice(){		
		loadProp("a_little_config_pro.txt", "a_little_config.txt");
		ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
	}
		
	/**
	 * 轮询数据库，通知参与者 hegx 2016-09-30 14:00
	 */
	public void sendMXNotice(String url){
		List<Meetingcreate> items = Meetingcreate.me.getAllSend("0");		
		if (items == null || items.size() == 0){
			return;
		}		
    	QiYeNewsMsg outMsg = new QiYeNewsMsg();
    	outMsg.setAgentid("0");
		outMsg.setSafe("0");
    	List<Article> arcls = new ArrayList<Article>();
		for (int row=0;row<items.size();row++){			
			String chr = items.get(row).getStr("chr"); //获取参与人
			if (chr == null || "".equals(chr)){
				continue;
			}
			Article article = getArticle(items.get(row),url);										
			arcls.add(article);			
			News news = new News();
			news.setArticles(arcls);			
			outMsg.setTouser(chr.replaceAll(",", "|"));  //设置发送给那个家伙
			outMsg.setNews(news);	
			ApiResult sendTextMsg = SendMessageApi.sendNewsMsg(outMsg);
			System.out.println("消息发送结果返回值: " + sendTextMsg.getJson());
			arcls.clear();
			Meetingcreate.me.setIsSend(items.get(row).getInt("xh"), 1);	
		}		
	}	
	
	private Article getArticle(Meetingcreate item,String url){
		String jsonss = getUserInfo(item.getStr("fqr"));
		JSONObject jsonUser = JSONObject.parseObject(jsonss);
		String name = jsonUser.getString("name");
		
		Article article = new Article();
		article.setTitle("会议提醒:" + item.getStr("name"));
		article.setDescription("发起人:" + 
				name + "\n会议地点:" + 
				item.getStr("place") + "\n开始时间:" + 
				item.getTimestamp("starttime").toString().substring(0,15) + "\n结束时间:" + 
				item.getTimestamp("finishtime").toString().substring(0,15));		
		article.setUrl(url + "qymeetingdetail?xh=" + item.getInt("xh"));
		return article;
	}
	
	/**
	 * 获取所有用户
	 * @return
	 */
	public String getUserList(){
		ApiResult apiResult = ConUserApi.getDepartmentUserList("1", "1", "0");
		String jsonStr = apiResult.getJson();
		JSONObject jsonObject = JSONObject.parseObject(jsonStr);		
		JSONArray jsonArray = JSONArray.parseArray(jsonObject.get("userlist").toString());
		StringBuilder sb = new StringBuilder();
		for(int k=0;k<jsonArray.size();k++){  
			JSONObject jsonObj = JSONObject.parseObject(jsonArray.get(k).toString());
			sb.append("<div class=\"sort_list\">\r\n");
			sb.append("	<div class=\"num_logo\">\r\n");
			sb.append("		<img src=\"" + jsonObj.get("avatar") + "\">\r\n");
			sb.append("	</div>\r\n");
			sb.append("	<div class=\"num_name\">" + jsonObj.get("name") + "</div>\r\n");
			sb.append("	<div class=\"num_check\">\r\n");
			sb.append("		<i class=\"weui_icon_circle\" userid=\"" + jsonObj.get("userid") + "\"></i>\r\n");
			sb.append("	</div>\r\n");    
			sb.append("</div>\r\n");  
        }								
		return sb.toString();
	} 
	
	/**
	 * 获取所有用户,更新到本地DB
	 * @return
	 */
	public String setWeiXinUserToLocalDB(){
		ApiResult apiResult = ConUserApi.getDepartmentUserList("1", "1", "0");
		String jsonStr = apiResult.getJson();
		JSONObject jsonObject = JSONObject.parseObject(jsonStr);		
		JSONArray jsonArray = JSONArray.parseArray(jsonObject.get("userlist").toString());
		StringBuilder sb = new StringBuilder();
		for(int k=0;k<jsonArray.size();k++){  
			JSONObject jsonObj = JSONObject.parseObject(jsonArray.get(k).toString());
			String departs = jsonObj.get("department").toString();
			int mpos = departs.lastIndexOf(",");
			if (mpos == -1){
				mpos = 0;
			}
			String dnum = departs.substring(mpos + 1,departs.indexOf("]"));
			Mmsryxx.me.save(jsonObj.get("userid"),jsonObj.get("name"),
					dnum,jsonObj.get("position"),jsonObj.get("mobile"), 
					jsonObj.get("gender"),jsonObj.get("avatar"),
					jsonObj.get("status"));			
        }								
		return sb.toString();
	} 
	
	/**
	 * 获取用户信息
	 * @param userid
	 * @return
	 */
	public String getUserInfo(String userid){
		ApiResult apiResult = ConUserApi.getUser(userid);
		return apiResult.getJson();
	}
	
	public String getDepartmentInfo(String departid){
		ApiResult apiResult=ConDepartmentApi.getDepartment(departid);
		return apiResult.getJson();
	}
	
	/**
	 * 如果生产环境配置文件存在，则优先加载该配置，否则加载开发环境配置文件
	 * @param pro 生产环境配置文件
	 * @param dev 开发环境配置文件
	 */
	private void loadProp(String pro, String dev) {
		try {
			PropKit.use(pro);
		}
		catch (Exception e) {
			PropKit.use(dev);
		}
	}
	
	/**
	 * 如果要支持多公众账号，只需要在此返回各个公众号对应的  ApiConfig 对象即可
	 * 可以通过在请求 url 中挂参数来动态从数据库中获取 ApiConfig 属性值
	 */
	private ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();		
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setCorpId(PropKit.get("corpId"));
		ac.setCorpSecret(PropKit.get("secret"));						
		/**
		 *  是否对消息进行加密，对应于微信平台的消息加解密方式：
		 *  1：true进行加密且必须配置 encodingAesKey
		 *  2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "在配置文件中设置该属性"));
		return ac;
	}		
}
